﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
namespace LitTools
{
    /// <summary>
    /// 日志管理
    /// </summary>
    public partial class LogManager : Singleton<LogManager>, ISingleton
    {
        int ISingleton.Order => 100;
        /// <summary>
        /// 堆栈追踪
        /// </summary>
        public bool StackTrace { get; set; }
        /// <summary>
        /// 记录间隔
        /// </summary>
        public float RecordInterval
        {
            get => recordInterval;
            set
            {
                if (value <= 0.1f)
                {
                    Debug.LogError("record interval should not less than 0.1f");
                }
                else
                {
                    recordInterval = value;
                }
            }
        }

        private string logFileName;//日志文件名
        private string logFilePath;//日志文件路径
        private float recordInterval = 1f;//记录间隔
        private float lastRecordTime = float.MinValue;//上次记录事件
        private StringBuilder logContent;//记录内容
        private bool isDirty;//脏标记

        void ISingleton.OnInit()
        {
            logFileName = $"{System.DateTime.Now.Year}_{System.DateTime.Now.Month}_{System.DateTime.Now.Day}"
                        + $"#{System.DateTime.Now.Hour}_{System.DateTime.Now.Minute}_{System.DateTime.Now.Second}";
            logFilePath = "LogFile/" + logFileName + ".txt";
            Application.logMessageReceived += OnLogReceived;
            Debug.Log("LogManager start recording");
        }

        void ISingleton.OnUpdate()
        {
            if (!isDirty) return;
            if (Time.realtimeSinceStartup - lastRecordTime < recordInterval) return;

            PresistentFileUtility.SaveFile(logFilePath, logContent.ToString(), true);
            logContent.Clear();
            lastRecordTime = Time.realtimeSinceStartup;
            isDirty = false;
        }

        void ISingleton.OnDestroy()
        {
            Application.logMessageReceived -= OnLogReceived;
        }

        private void OnLogReceived(string condition, string stackTrace, LogType type)
        {
            if (logContent == null)
                logContent = new StringBuilder();
            string line = $"[{System.DateTime.Now.ToShortTimeString()}] ({type}) \"{condition}\" \n";
            if (StackTrace)
                line += stackTrace + "\n";
            logContent.Append(line);
            isDirty = true;
        }
    }
}